package com.study.quiz.controller;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.study.quiz.dto.CommentDTO;
import com.study.quiz.dto.CommentResponseDTO;
import com.study.quiz.dto.QuestionDTO;
import com.study.quiz.enums.CommentTypeEnum;
import com.study.quiz.pojo.Question;
import com.study.quiz.pojo.User;
import com.study.quiz.service.CommentService;
import com.study.quiz.service.QuestionService;
import com.study.quiz.utils.ErrorIndexUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author CJunGod
 * @create 2020-03-07 11:03
 **/
@Controller
public class QuestionController {

    @Resource
    private QuestionService questionService;

    @Resource
    private ErrorIndexUtil errorIndexUtil;

    @Resource
    private CommentService commentService;

    @GetMapping("/question/{id}")
    public String question(@PathVariable(name = "id") Integer questionId,
                           ModelMap modelMap, HttpServletRequest request) {
        if (StringUtils.isNotEmpty(errorIndexUtil.getErrorMesg())) {
            modelMap.put("publishError", errorIndexUtil.getErrorMesg());
            errorIndexUtil.errorIndex(null);
        }
        QuestionDTO questionDTO = questionService.findById(questionId);
        questionService.updateView(questionDTO.getQuestion().getId(), System.currentTimeMillis());
        List<CommentResponseDTO> commentDTOList = commentService.listByTargetId(questionId, CommentTypeEnum.QUESTION.getType());
        List<QuestionDTO> questionList = questionService.selectRelated(questionDTO);

        modelMap.put("questionDto", questionDTO);
        modelMap.put("comments", commentDTOList);
        modelMap.put("relatedQuestions", questionList);
        return "question";
    }
}
